import saleOrdersAPI from '../../../common/api/breedsales/orderbills.api.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Page } from "../../../common/serve-request.js";

(function (window, document, $) {
    let _vm, savetype, entriesmater, getEntryInfo = [], nextEntryId = 1, operaEntryId, saveEntry, checkSale, _specLevelArry = [];
    const BaseCfgUrl = Utils.CurDomain.BaseCfgUrl;
    const _json = Utils.ParsingUrl(window.location);

    $(async function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    "entries": [
                        {
                            "farmOrgId": "",
                            "farmOrgName": "",
                            "deiverId": "",
                            "deiverName": "",
                            "deiverNumCode": "",
                            "deiverPhone": "",
                            "shipRegion": "",
                            "shipAddress": "",
                            "deliveryRegion": "",
                            "deliveryAddress": "",
                            "specLevel": "",
                            "specLevelType": "",
                            "carNo": "",
                            "transferCarNo": "",
                            "remark": "",
                            "planQty": '',
                            "unitPrice": '',
                            "weight": '',
                            "estimatedAvgWeight": '',
                            "isGift": false,
                            "materialId": "",
                            "materialName": "",
                            "materialNumCode": "",
                            "baseMeasureUnit": "",
                            "subMeasureUnit": "",
                            "breedBatchId": "",
                            "breedBatchName": ""
                        }
                    ],
                    pickerData: []
                }
            },
            methods: {
                submit() {
                    savedata()
                }
            }
        });
        await _initCommand()
        _select2Info();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        if (Utils.IsNotNull(getEntryInfo)) {
            _vm.entries = [];
            _vm.entries.push(getEntryInfo.pop());
        }

        // 编辑分录
        if (Utils.IsNotNull(getUrlKey('operaEntryId'))) {
            $("title").text("销售订单明细-编辑");
            operaEntryId = Number(getUrlKey('operaEntryId')) - 1
            _vm.entries.pop()
            _vm.entries.push(JSON.parse(Utils.GetSessionStorage("getEntryInfo"))[operaEntryId]);

        }
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            if (Utils.IsNotNull(getUrlKey("id"))) {
                location.href = `../saleorders/addsaleorders.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&id=${getUrlKey("id")}&cstmId=${_json.cstmId}`;
            }
            else {
                location.href = `../saleorders/addsaleorders.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&cstmId=${_json.cstmId}`;
            }
        });

        //获取行政区划信息
        saleOrdersAPI.getDistricts().then(res => {
            _vm.pickerData = _getJsonTree(res, "e8wa")
        });

        //打开行政区划弹框
        $(document).on('click', '#shipRegion', function () {
            weui.picker(_vm.pickerData, {
                onChange: function (result) {
                    //console.log(result);
                },
                onConfirm: function (result) {
                    let address = `${result[0].label}${result[1]?.label || ''}${result[2]?.label || ''}${result[3]?.label || ''}`;
                    let details = `${result[0].value};${result[1]?.value || ''};${result[2]?.value || ''};${result[3]?.value || ''}|${result[0].label};${result[1]?.label || ''};${result[2]?.label || ''};${result[3]?.label || ''}`;
                    $('#shipAddressPack').val(details)
                    $('#shipRegion').val(address)
                },
                id: 'multiPickerBtn'
            });
        });
        $(document).on('click', '#deliveryRegion', function () {
            weui.picker(_vm.pickerData, {
                onChange: function (result) {
                    //console.log(result);
                },
                onConfirm: function (result) {
                    let address = `${result[0].label}${result[1]?.label || ''}${result[2]?.label || ''}${result[3]?.label || ''}`;
                    let details = `${result[0].value};${result[1]?.value || ''};${result[2]?.value || ''};${result[3]?.value || ''}|${result[0].label};${result[1]?.label || ''};${result[2]?.label || ''};${result[3]?.label || ''}`;
                    $('#deliveryAddressPack').val(details)
                    $('#deliveryRegion').val(address)
                }
            });
        });

        //运输车牌
        //$(document).on("input propertychange", '#carNo', function () {
        //    let carNo = $(`#carNo`).val().toUpperCase();
        //    $(`#carNo`).val(carNo);
        //});
        ////中转车牌
        //$(document).on("input propertychange", '#transferCarNo', function () {
        //    let transferCarNo = $(`#transferCarNo`).val().toUpperCase();
        //    $(`#transferCarNo`).val(transferCarNo);
        //});
    }

    //递归
    const _getJsonTree = (data, parentId) => {
        var itemArr = [];
        for (var i = 0; i < data.length; i++) {
            var node = data[i];
            if (node.parent.id === parentId) {
                var newNode = {
                    value: node.id,
                    label: node.name,
                    children: _getJsonTree(data, node.id),
                };
                itemArr.push(newNode);
            }
        }
        return itemArr;
    }

    // 物料
    const _master = async () => {
        let allMaterial = await saleOrdersAPI.postMaterial()
        let allMaterialInfo = allMaterial.items.filter(item => item.numCode.substring(0, 2) == '14')
        $(`#materialid`).select2({
            placeholder: '请选择物料...', //默认文字提示
            language: "zh-CN",//汉化
            data: allMaterialInfo.map(item => {
                return {
                    id: item.id,
                    text: `${item.name}(${item.numCode})`,
                    ...item
                }
            }),
        });

        // $(`#materialid`).select2({
        //     language: "zh-CN",
        //     ajax: {
        //         url: `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`,
        //         dataType: 'json',
        //         type: 'GET',
        //         headers: {
        //             Authorization: "Bearer " + Utils.GetSNAuthAT(),
        //             "Content-Type": 'application/json',
        //             Accept: 'application/json',
        //             "Access-Control-Allow-Origin": '*',
        //             "Access-Control-Allow-Headers": "X-Requested-With",
        //             "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS"
        //         },
        //         data: function (params) {
        //             return {
        //                 MGroupId: DictionaryType.MATERIAL_TYPE,
        //                 SearchInfo: params.term,
        //                 PageSize: 10,
        //                 PageIndex: (params.page || 1) - 1
        //             };
        //         },
        //         processResults: function (data, params) {
        //             params.page = params.page || 1;
        //             let _data = data.data.items.map(item => {
        //                 item.text = `${item.name}(${item.numCode})`;
        //                 return item;
        //             });
        //             return {
        //                 results: _data,// 后台返回的数据集
        //                 pagination: {
        //                     more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
        //                 }
        //             };
        //         },
        //         minimumInputLength: 1,
        //     }
        // });
        $("#materialid").setSelectValue();
        if (Utils.IsNotNull(_vm.entries[0].materialId)) {
            $(`#materialid`).setSelectValue(_vm.entries[0].materialId, _vm.entries[0].materialName);
        }
    }

    //下拉框数据
    const _select2Info = () => {
        //农场
        saleOrdersAPI.queryDepList(_json.orgId, 1, '210').then(res => {
            $(`#farmOrgId`).select2({
                placeholder: '请选择农场...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        //text: `${item.name}(${item.numCode})`,
                        text: item.name,
                        name: item.name
                    }
                }),
            });
            $("#farmOrgId").setSelectValue();

            $('#farmOrgId').on("select2:select", async function () {
                $('#breedBatchId').prop('disabled', false);
                let json = await saleOrdersAPI.getFarms($(this).val());
                if (Utils.IsNotNull(json)) {
                    let details = json.region.split('|')[1].split(';');
                    $('#shipAddress').val(_vm.entries[0].shipAddress);
                    $('#shipRegion').val(details[0] + details[1] + details[2] + details[3]);
                    $('#shipAddressPack').val(json.region);
                } else {
                    $('#shipAddress').val('');
                    $('#shipRegion').val('');
                    $('#shipAddressPack').val('');
                }
            });

            if (Utils.IsNotNull(_vm.entries[0].farmOrgId)) {
                _initFarmsAddress(_vm.entries[0].farmOrgId);

                $(`#farmOrgId`).setSelectValue(_vm.entries[0].farmOrgId);
                $('#planQty').val(_vm.entries[0].planQty || _vm.entries[0].orderCount);
                $('#estimatedAvgWeight').val(_vm.entries[0].estimatedAvgWeight);
                $('#unitPrice').val(_vm.entries[0].unitPrice);
                $('#isGift').prop('checked', _vm.entries[0].isGift);

                if (Utils.IsNotNull(_vm.entries[0].shipRegion)) {
                    let details = _vm.entries[0].shipRegion.split('|')[1].split(';');
                    $('#shipAddress').val(_vm.entries[0].shipAddress);
                    $('#shipRegion').val(details[0] + details[1] + details[2] + details[3]);
                    $('#shipAddressPack').val(_vm.entries[0].shipRegion);
                } else {
                    $('#shipAddress').val('');
                    $('#shipRegion').val('');
                    $('#shipAddressPack').val('');
                }
                if (Utils.IsNotNull(_vm.entries[0].deliveryRegion)) {
                    let delivery = _vm.entries[0].deliveryRegion.split('|')[1].split(';')
                    $('#deliveryAddress').val(_vm.entries[0].deliveryAddress);
                    $('#deliveryRegion').val(delivery[0] + delivery[1] + delivery[2] + delivery[3]);
                    $('#deliveryAddressPack').val(_vm.entries[0].deliveryRegion);
                } else {
                    $('#deliveryAddress').val('');
                    $('#deliveryRegion').val('');
                    $('#deliveryAddressPack').val('');
                }
            }
            if (Utils.IsNotNull(getUrlKey('operaEntryId'))) {
                $('#carNo').val(_vm.entries[0].carNo);
                $('#deiverName').val(_vm.entries[0].deiverName);
                $('#deiverPhone').val(_vm.entries[0].deiverPhone);
                $('#transferCarNo').val(_vm.entries[0].transferCarNo);
                $('#remark').val(_vm.entries[0].remark);
            }
        });
        //销售品类
        requestDict(DictionaryType.LEVEL_TYPE).then(res => {
            _specLevelArry = res.data;
            $('#specLevel').select2({
                placeholder: '请选择销售品类...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            $("#specLevel").setSelectValue();
            if (Utils.IsNotNull(_vm.entries[0].specLevel)) {
                $(`#specLevel`).setSelectValue(_vm.entries[0].specLevel);
            }

            //养殖批次
            Select2Page($(`#breedBatchId`), `${BaseCfgUrl}/breedbatchs/rlist`, (params) => {
                return JSON.stringify({
                    farmOrgId: $(`#farmOrgId`).val(),
                    fiOrgId: '',
                    tags: '',
                    name: params.term,
                    isEnd: false,
                    pageSize: 20,
                    pageIndex: (params.page || 1) - 1
                })
            }, "POST", {
                templateResult: function (res) {
                    return `${res.name == undefined ? res.text : res.name}`;
                }
            });
            if (Utils.IsNotNull(_vm.entries[0].breedBatchId)) {
                $(`#breedBatchId`).prop('disabled', false);
                $(`#breedBatchId`).setSelectValue(_vm.entries[0].breedBatchId, _vm.entries[0].breedBatchName);
            }
            _master();
        });

        // 销售单位
        let pricMesuUnit = [
            { id: 1, text: 'TOU' },
            { id: 2, text: 'KG' }
        ]
        $('#pricMesuUnit').empty().select2({
            placeholder: '请选择销售单位...', //默认文字提示
            language: "zh-CN",//汉化
            data: pricMesuUnit
        });

        if (Utils.IsNotNull(_vm.entries[0].baseMeasureUnit)) {
            $('#pricMesuUnit').val(_vm.entries[0].baseMeasureUnit == 'KG' ? 2 : 1).trigger('change');
        }
        else {
            $('#pricMesuUnit').val(2).trigger('change');
            _vm.entries[0].baseMeasureUnit = 'KG'
        }
        // 选择 销售单位
        $('#pricMesuUnit').on('select2:select', function () {
            _vm.entries[0].baseMeasureUnit = $(this).select2('data')[0]?.text
        })


    }

    // 保存
    const savedata = () => {
        //车牌
        const LICENSE_PLATE = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
        //保留两位小数
        const FLOAT_Method = /^\d+(\.\d{1,2})?$/;
        //保留三位小数
        const Three_Method = /^\d+(\.\d{1,3})?$/;
        //电话号码
        const PHONE_VERIFICATION = /^1[3456789]\d{9}$/;

        if (!Utils.IsNotNull($(`#farmOrgId`).val())) {
            return $.toptip(`请选择农场!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#breedBatchId`).val())) {
            return $.toptip(`请选择养殖批次!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#materialid`).select2('data'))) {
            return $.toptip(`请选择物料!`, 'warning');
        }
        if (!Utils.IsNotNull($('#shipRegion').val())) {
            return $.toptip(`请选择发货地址!`, 'warning');
        }
        if (!Utils.IsNotNull($('#shipAddress').val())) {
            return $.toptip(`发货详细地址不能为空!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#specLevel`).select2('data'))) {
            return $.toptip(`请选择销售品类!`, 'warning');
        }
        if (!Utils.IsNotNull($('#planQty').val())) {
            return $.toptip(`数量不能为空!`, 'warning');
        }
        if (!(/(^[1-9]\d*$)/.test(($('#planQty').val())))) {
            return $.toptip(`请输入大于0的整数!`, 'warning');
        }
        if (!Utils.IsNotNull($('#estimatedAvgWeight').val())) {
            return $.toptip(`预估均重不能为空!`, 'warning');
        }
        if (Number($('#estimatedAvgWeight').val()) == 0 || !(FLOAT_Method.test(($('#estimatedAvgWeight').val())))) {
            return $.toptip(`预估均重必须大于0且小数点后最多为两位!`, 'warning');
        }
        if (!Utils.IsNotNull($('#unitPrice').val())) {
            return $.toptip(`基础单价不能为空!`, 'warning');
        }
        if (Number($('#unitPrice').val()) == 0 || !(Three_Method.test(($('#unitPrice').val())))) {
            return $.toptip(`基础单价必须大于0且小数点后最多为三位!`, 'warning');
        }
        if (!Utils.IsNotNull($('#deiverName').val())) {
            return $.toptip(`司机姓名不能为空!`, 'warning');
        }
        if (!Utils.IsNotNull($('#deiverPhone').val())) {
            return $.toptip(`司机电话号码不能为空!`, 'warning');
        }
        if (!(PHONE_VERIFICATION.test(($('#deiverPhone').val())))) {
            return $.toptip(`请输入正确的电话号码!`, 'warning');
        }
        if (!Utils.IsNotNull($('#carNo').val())) {
            return $.toptip(`运输车牌不能为空!`, 'warning');
        }
        let carNo = $(`#carNo`).val().toUpperCase();
        if (!carNo.match(LICENSE_PLATE)) {
            return $.toptip(`请输入正确的运输车牌!`, 'warning');
        }
        if (Utils.IsNotNull($(`#transferCarNo`).val())) {
            let transferCarNo = $(`#transferCarNo`).val().toUpperCase();
            if (!transferCarNo.match(LICENSE_PLATE)) {
                return $.toptip(`请输入正确的中转车牌!`, 'warning');
            }
        }
        if (!Utils.IsNotNull($('#deliveryRegion').val())) {
            return $.toptip(`收货地址不能为空!`, 'warning');
        }
        if (!Utils.IsNotNull($('#deliveryAddress').val())) {
            return $.toptip(`收货详细地址不能为空!`, 'warning');
        }
        let details = $('#shipAddressPack').val().split("|");
        if (!Utils.IsNotNull(details[0].split(';')[2])) {
            return $.toptip(`发货地址至少选到区县!`, 'warning');
        }
        let delivery = $('#deliveryAddressPack').val().split("|");
        if (!Utils.IsNotNull(delivery[0].split(';')[2])) {
            return $.toptip(`收货地址至少选到区县!`, 'warning');
        }

        entriesmater = {
            "seq": Number(nextEntryId),
            "farmOrgId": $("#farmOrgId").select2('data')[0].id,
            "farmOrgName": $("#farmOrgId").select2('data')[0].name,
            "deiverId": '',
            "deiverName": $(`#deiverName`).val(),
            "deiverNumCode": "",
            "deiverPhone": $(`#deiverPhone`).val(),
            "shipRegion": $('#shipAddressPack').val(),
            "shipAddress": $('#shipAddress').val(),
            "deliveryRegion": $('#deliveryAddressPack').val(),
            "deliveryAddress": $('#deliveryAddress').val(),
            "specLevel": $('#specLevel').val(),
            "specLevelType": _specLevelArry.find(s => s.value == $('#specLevel').val()).displayName,
            "carNo": $('#carNo').val().toUpperCase(),
            "transferCarNo": $('#transferCarNo').val().toUpperCase(),
            "remark": $('#remark').val(),
            "planQty": $('#planQty').val(),
            "unitPrice": $('#unitPrice').val() || 0,
            "weight": $('#weight').val(),
            "estimatedAvgWeight": $('#estimatedAvgWeight').val(),
            "isGift": $("#isGift").prop("checked"),
            "materialId": $(`#materialid`).select2('data')[0].id,
            "materialName": $(`#materialid`).select2('data')[0].name || _vm.entries[0].materialName,
            "materialNumCode": $(`#materialid`).select2('data')[0].numCode || _vm.entries[0].materialNumCode,
            "baseMeasureUnit": _vm.entries[0].baseMeasureUnit,
            "subMeasureUnit": $(`#materialid`).select2('data')[0].subMeasureUnit || _vm.entries[0].subMeasureUnit,
            "breedBatchId": $(`#breedBatchId`).select2('data')[0].id,
            "breedBatchName": $(`#breedBatchId`).select2('data')[0].text,
            'customerId': _json.cstmId
        }
        if (Utils.IsNotNull(getUrlKey('operaEntryId'))) {
            entriesmater.seq = Number(getUrlKey('operaEntryId'))
        }
        if (Utils.IsNotNull(Utils.GetSessionStorage("getEntryInfo"))) {
            getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        }
        checkSale = getEntryInfo
        // 编辑分录
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            delete checkSale[operaEntryId]
            savetips()
        }
        // 新增分录
        else {
            // 过滤出和当前选择的一样的物料
            let checkSaleflag = checkSale.filter(function (item, index) {
                return item.carNo === entriesmater.carNo
            })
            if (Utils.IsNotNull(checkSaleflag)) {
                let flagfalse = checkSaleflag.some(item => {
                    return item.isGift === false && $('#isGift').is(':checked') === false
                })
                if (flagfalse) {
                    return $.toptip(`运输车牌号重复,请重新填写!`, 'warning');
                }
                let flagtrue = checkSaleflag.some(item => {
                    return item.isGift === true && $('#isGift').is(':checked') === true
                })
                if (flagtrue) {
                    return $.toptip(`运输车牌号重复,请重新填写!`, 'warning');
                }
                else {
                    savetips()
                }
            }
            else {
                savetips()
            }
        }

    }

    // 保存提示
    const savetips = () => {
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认${savetype}该分录？</div>
					</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        //先获取分录的内容
                        if (Utils.IsNotNull(Utils.GetSessionStorage("getEntryInfo"))) {
                            getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
                        }
                        // 编辑分录
                        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
                            // 存储下一个分录的序号
                            let _info = [];
                            nextEntryId = Number(nextEntryId)
                            getEntryInfo[operaEntryId] = entriesmater;
                            $.each(getEntryInfo, function (i, v) {
                                v.seq = i + 1;
                                _info.push({ ...v });
                            });
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", _info))
                        }
                        // 新增分录
                        else {
                            let _info = [];
                            nextEntryId = Number(nextEntryId) + 1
                            getEntryInfo.push(entriesmater);
                            $.each(getEntryInfo, function (i, v) {
                                v.seq = i + 1;
                                _info.push({ ...v });
                            });
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", _info))
                        }
                        location.href = `./addsaleorders.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&cstmId=${_json.cstmId}`;

                        if (Utils.IsNotNull(getUrlKey("id"))) {
                            location.href = `./addsaleorders.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&id=${getUrlKey("id")}&cstmId=${_json.cstmId}`;
                        }
                        else {
                            location.href = `./addsaleorders.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&cstmId=${_json.cstmId}`;
                        }
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    // 解决字段过长
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    //获取养殖场地址
    const _initFarmsAddress = async (id) => {
        let json = await saleOrdersAPI.getFarms(id);

        let details = json.region.split('|')[1].split(';');
        $('#shipAddress').val(_vm.entries[0].shipAddress);
        $('#shipRegion').val(details[0] + details[1] + details[2] + details[3]);
        $('#shipAddressPack').val(json.region);
    }

})(window, document, jQuery)